/*
 * Protocol.c
 *
 *  Created on: 26-06-2012
 *      Author: Mati
 */

#include "Protocol.h"

ProtocolMarkers PMarker = {_SOF,
		_main,
		_pid,
		_prepareMode,
		_workMode,
		_twr,
		_autoMode,
		_userMode,
		_temperature,
		_current,
		_voltage,
		_dac_voltage,
		_adc_voltage,
		_speaker,
		_debug,
		_resistance,
		_mode,
		_kp,
		_ki,
		_kd,
		_prec300,
		_prec20,
		_precUser,
		_ptime1,
		_ptime2,
		_ptime3,
		_ptime4,
		_ptime5,
		_ptemp1,
		_ptemp2,
		_ptemp3,
		_ptemp4,
		_ptemp5,
		_wtime1,
		_wtime2,
		_wtemp1,
		_wtemp2,
		_A_TWR,
		_B_TWR
						};

//initial values
ProtocolValues PVal =
		{       1,	//autoMode
				0,	//userMode
        0,// temperature,
        0,// current,
        0,// voltage,
        500,//dac_voltage
        0,// speaker,
        0,// debug,
        0,//resistance

        //pid
        4.2,// kp,
        0.1,// ki,
        0,// kd,

        1,// prec300,
        0,// prec20,
        0,// precUser,

        //prepareMode
        60,// ptime1,
        60,// ptime2,
        60,// ptime3,
        60,// ptime4,
        60,// ptime5,

        50,// ptemp1,
        100,// ptemp2,
        150,// ptemp3,
        250,// ptemp4,
        350,// ptemp5,

        //workMode
        7,		// wtime1,
        3,		// wtime2,
        25,		// wtemp1,
        200,	// wtemp2
        //twr
        0.09,		//a-twr
		302.1};		//b-twr

ProtocolAddress PAddress =
		{		_addr_autoMode,
				_addr_userMode,
				_addr_speaker,
				_addr_debug,
				_addr_kp,
				_addr_ki,
				_addr_kd,
				_addr_prec300,
				_addr_prec20,
				_addr_precUser,
				_addr_ptime1,
				_addr_ptime2,
				_addr_ptime3,
				_addr_ptime4,
				_addr_ptime5,
				_addr_ptemp1,
				_addr_ptemp2,
				_addr_ptemp3,
				_addr_ptemp4,
				_addr_ptemp5,
				_addr_wtime1,
				_addr_wtime2,
				_addr_wtemp1,
				_addr_wtemp2,
				_addr_A_TWR,
				_addr_B_TWR
								};

//uint8_t issent = 3;

void Send(uint8_t parameter, uint8_t *pVal)
{
	uint8_t buff[7] = {PMarker.SOF, PMarker.main, parameter};

	buff[3] = (uint8_t)*(pVal+3);
	buff[4] = (uint8_t)*(pVal+2);
	buff[5] = (uint8_t)*(pVal+1);
	buff[6] = (uint8_t)*(pVal);

	SendBufferThruUART(buff, 7);
}

void SendBufferThruUART(uint8_t *buffer, uint8_t size)
{
	while(size>0)
	{
		UART_Sendchar(*buffer++);
		size--;
	}
}

//funkcja konwertująca wartosc 16-bitową na float'a - starsze 8 bitów to częsć przed przecinkiem, młodsze 8 bitów - częsć po przecinku
float ConvertUInt16ToFloat(uint16_t u16val)
{
	uint8_t msb = (u16val&0xFF00)>>8;
	uint8_t lsb = u16val&0x00FF;

	return ( (float)msb + (float)lsb/100 );
}

uint16_t ConvertFloatToUInt16(float fval)
{
	uint8_t u8msb = (uint8_t) fval;
	uint8_t u8lsb;
	float ftemp = (fval- (float)u8msb)*100;
	u8lsb = (uint8_t) ftemp;

	return (uint16_t) ((u8msb<<8) | u8lsb);
}
